<template>
    <div class="crud-container">
        <!-- 搜索区域 -->
        <div class="search-area">
            <el-form :inline="true" :model="searchForm" class="search-form">
                <el-form-item label="角色名称" class="el-formitem">
                    <el-select v-model="searchForm.role" placeholder="请选择角色名称" clearable>
                        <el-option v-for="item in roleOptions" :key="item.roleId" :label="item.description"
                            :value="item.role" />
                    </el-select>
                </el-form-item>
                <el-form-item label="菜单名称" class="el-formitem">
                    <el-select v-model="searchForm.menuName" placeholder="请选择菜单名称" clearable>
                        <el-option v-for="item in roleOptions1" :key="item.menuId" :label="item.menuName"
                            :value="item.menuName" />
                    </el-select>
                </el-form-item>
                <el-form-item label="状态">
                    <el-select v-model="searchForm.rolePermissionState" placeholder="请选择状态" clearable>
                        <el-option label="正常" value="0" />
                        <el-option label="停用" value="1" />
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">
                        <el-icon>
                            <Search />
                        </el-icon>搜索
                    </el-button>
                    <el-button @click="resetSearch">
                        <el-icon>
                            <Refresh />
                        </el-icon>重置
                    </el-button>
                </el-form-item>
            </el-form>
        </div>

        <!-- 操作按钮区域 -->
        <div class="operation-area">
            <el-button type="primary" @click="handleAdd">
                <el-icon>
                    <Plus />
                </el-icon>新增
            </el-button>
            <el-button type="danger" :disabled="!selectedRows.length" @click="handleBatchDelete">
                <el-icon>
                    <Delete />
                </el-icon>批量删除
            </el-button>
        </div>

        <!-- 表格区域 -->
        <div class="table-area">
            <el-table v-loading="loading" :data="tableData" border style="width: 100%"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="roleId" label="编号" width="80" />
                <el-table-column prop="role" label="角色名称" />
                <el-table-column prop="description" label="角色描述" />
                <el-table-column prop="menuName" label="菜单权限" />
                <el-table-column prop="rolePermissionState" label="状态" width="100">
                    <template #default="{ row }">
                        <el-tag :type="row.rolePermissionState === 0 ? 'success' : 'danger'">
                            {{ row.rolePermissionState === 0 ? '正常' : '停用' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="200" fixed="right">
                    <template #default="{ row }">
                        <el-button type="primary" link @click="handleEdit(row)">
                            <el-icon>
                                <Edit />
                            </el-icon>编辑
                        </el-button>
                        <el-button type="danger" link @click="handleDigDelete(row)">
                            <el-icon>
                                <Delete />
                            </el-icon>删除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>

        <!-- 分页区域 -->
        <div class="pagination-area">
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize"
                :page-sizes="[10, 20, 50, 100]" :total="total" layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>

        <!-- 新增表单 -->
        <el-dialog v-model="showAddDialog" title="新增角色" width="500px" :destroy-on-close="true">
            <el-form label-width="100px" :model="addForm" ref="formRef" :rules="rules">
                <el-form-item label="角色名称" prop="role">
                    <el-input v-model="addForm.role" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                    <el-input v-model="addForm.description" placeholder="请输入角色描述" />
                </el-form-item>
                <el-form-item label="分配菜单" prop="menuName" class="el-formitem">
                    <el-checkbox-group v-model="addForm.menuId">
                        <el-checkbox v-for="item in roleOptions1" :key="item.menuId" :label="item.menuName" :value="item.menuId">
                            {{ item.menuName }}
                        </el-checkbox>
                    </el-checkbox-group>
                </el-form-item>

                <!-- <el-form-item label="状态" prop="adminState">
                    <el-select v-model="addForm.adminState" placeholder="请选择状态">
                        <el-option label="正常" :value="0" />
                        <el-option label="停用" :value="1" />
                    </el-select>
                </el-form-item> -->
            </el-form>
            <template #footer>
                <el-button @click="showAddDialog = false">取消</el-button>
                <el-button type="primary" @click="submitAddForm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 编辑表单 -->
        <el-dialog v-model="showUpDialog" title="修改角色" width="500px" :destroy-on-close="true">
            <el-form label-width="100px" :model="upForm" ref="formRef" :rules="rules">
                <el-form-item label="角色名称" prop="role">
                    <el-input v-model="upForm.role" placeholder="请输入角色名称" />
                </el-form-item>
                <el-form-item label="角色描述" prop="description">
                    <el-input v-model="upForm.description" placeholder="请输入角色描述" />
                </el-form-item>
                <el-form-item label="状态" prop="rolePermissionState">
                    <el-select v-model="upForm.rolePermissionState" placeholder="请选择状态">
                        <el-option label="正常" :value="0" />
                        <el-option label="停用" :value="1" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <el-button @click="showUpDialog = false">取消</el-button>
                <el-button type="primary" @click="submitUpForm">确定</el-button>
            </template>
        </el-dialog>

        <!-- 删除确认弹窗 -->
        <el-dialog v-model="dialogVisible" title="确认删除" width="30%" :before-close="handleClose">
            <span>你确定要删除这条数据吗？此操作不可恢复。</span>
            <template #footer>
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleDelete">确认</el-button>
            </template>
        </el-dialog>

        <!-- 删除确认弹窗 -->
        <el-dialog v-model="dialogVisible1" title="确认删除" width="30%" :before-close="handleClose">
            <span>你确定要删除这些数据吗？此操作不可恢复。</span>
            <template #footer>
                <el-button @click="dialogVisible1 = false">取消</el-button>
                <el-button type="primary" @click="handleDelete1">确认</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import { Fold, Expand, ArrowDown, Search, Refresh, Plus, Delete, Edit, View } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, messageConfig } from 'element-plus'
import request from '@/utils/request'
import dayjs from 'dayjs'

const router = useRouter()
const isCollapse = ref(false)
const menuList = ref([])
const activeMenu = ref('')
const showAddDialog = ref(false)
const showUpDialog = ref(false)
const roleOptions = ref([])
const roleOptions1 = ref([])
const formRef = ref(null)
// 控制弹窗显示
const dialogVisible = ref(false)
const dialogVisible1 = ref(false)

const addForm = ref({
    role: '',
    description: '',
    menuId: []
})

const upForm = ref({
    role: '',
    description: '',
    rolePermissionState: ''
})

const rules = {
    role: [
        { required: true, message: '请选择角色名称', trigger: 'change' },
        { pattern: /^[\u4e00-\u9fa5]+$/, message: '角色名称必须为中文', trigger: 'blur' }
    ],
    description: [
        { required: true, message: '请输入角色描述', trigger: 'blur' },
        { pattern: /^[\u4e00-\u9fa5]+$/, message: '角色描述必须为中文', trigger: 'blur' }
    ],
    rolePermissionState: [
        { required: true, message: '请选择状态', trigger: 'change' }
    ],
    menuId: [
        { required: true, message: '请至少选择一个菜单名称', trigger: 'change' }
    ]
}

// 页面加载时获取菜单
onMounted(() => {
    //获取菜单列表
    getMenuList()
    //管理员列表
    adminList()
    //角色选项列表
    fetchRoles()
    //菜单列表
    fetchMenus()
})

// 动态获取图标组件
const getIconComponent = (iconName) => {
    return ElementPlusIconsVue[iconName] || ElementPlusIconsVue['Menu']
}

// 获取菜单数据
const getMenuList = async () => {
    try {
        const userStr = sessionStorage.getItem('user')
        // if (!userStr) {
        //     ElMessage.error('用户未登录')
        //     router.push('/login')
        //     return
        // }

        const user = JSON.parse(userStr)
        const username = user.username


        request.get(`/menu/list?username=${encodeURIComponent(username)}`)
            .then(res => {
                // console.log(res);
                menuList.value = res.data.menu
                activeMenu.value = menuList.value[0].path
            }).catch(err => {
                console.log(err);

            })
    } catch (error) {
        ElMessage.error(error.message || '获取菜单失败')
        console.error('获取菜单失败:', error)
    }
}

// 点击菜单跳转
const handleMenuClick = (item) => {
    if (item.path) {
        router.push(item.path)
        activeMenu.value = item.path
    }
}

// 折叠菜单
const toggleSidebar = () => {
    isCollapse.value = !isCollapse.value
}

// 搜索表单数据
const searchForm = ref({
    role: '',
    menuName: '',
    rolePermissionState: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const selectedRows = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 搜索
const handleSearch = () => {
    // console.log(searchForm.value);

    request.get('/role/searchrolemenu', searchForm.value)
        .then((res) => {
            // console.log(res);
            if (res.code != 200) {
                ElMessage.error(res.message)
            }
            ElMessage.success("搜索成功！")
            tableData.value = res.data.list;
            // console.log(tableData.value);
            total.value = res.data.count;
            // adminList()
        }).catch((err) => {
            console.log(err);
        })
}

// 重置搜索
const resetSearch = () => {
    searchForm.value = {
        role: '',
        menuName: '',
        rolePermissionState: ''
    }
    ElMessage.success("重置成功！")
    adminList()
}

// 表格选择
const handleSelectionChange = (rows) => {
    selectedRows.value = rows
}

// 打开新增弹窗前重置表单
const handleAdd = () => {
    addForm.value = {
        role: '',
        description: '',
        menuId: []
    }
    showAddDialog.value = true
}

// 提交新增
const submitAddForm = () => {
    const menuId = ref([])
    menuId.value = addForm.value.menuId;

    formRef.value.validate((valid) => {
        if (valid) {
            request.post('/role/add', addForm.value , menuId)
                .then((res) => {
                    // console.log(res.message);
                    if(res != 200){
                        return ElMessage.error(res.message)
                    }
                    ElMessage.success(res.message)
                    addForm.value = {
                        role: '',
                        description: '',
                        menuId: []
                    }
                    showAddDialog.value = false
                    adminList()
                }).catch((err) => {
                    console.log(err);
                })
        } else {
            ElMessage.error('请填写完整信息！')
        }
    })
}

// 编辑
const handleEdit = (row) => {
    showUpDialog.value = true;
    // console.log(tableData.value);
    upForm.value.role = row.role;
    upForm.value.description = row.description;
    upForm.value.rolePermissionState = row.rolePermissionState;
    console.log(upForm.value);
}

// 提交编辑
const submitUpForm = () => {
    formRef.value.validate((valid) => {
        if (valid) {
            request.put('/role/upd', upForm.value)
                .then((res) => {
                    // console.log(res);
                    ElMessage.success(res.message);
                    showUpDialog.value = false;
                    adminList()
                }).catch((err) => {
                    console.log(err);
                })
        } else {
            ElMessage.error('请填写完整信息！')
        }
    })
}

//关闭前处理
const handleClose = (done) => {
    done() // 关闭弹窗
}
const rolePermissionState = ref(null);
const roleId = ref('');
// 打开删除弹窗
const handleDigDelete = (row) => {
    dialogVisible.value = true
    rolePermissionState.value = row.rolePermissionState;
    roleId.value = row.roleId;
    // console.log(row.roleId);
}

// 确认删除处理函数
const handleDelete = () => {
    dialogVisible.value = false
    // console.log(adminState.value);

    request.delete(`/role/del?rolePermissionState=${rolePermissionState.value}&roleId=${roleId.value}`)
        .then((res) => {
            // console.log(res);
            ElMessage.success(res.message)
            adminList()
        }).catch((err) => {
            console.log(err);
        })
}

// 批量删除
const handleBatchDelete = () => {
    dialogVisible1.value = true
}

// 确认批量删除处理函数
const handleDelete1 = () => {
    dialogVisible1.value = false
    // console.log(selectedRows.value);
    const ids = selectedRows.value.map(item => item.adminId);
    const state = selectedRows.value.map(item => item.adminState);
    // console.log(ids,state,1454615);


    request.delete(`/user/dele?adminState=${state}&adminId=${ids}`)
        .then((res) => {
            console.log(res);
            ElMessage.success(res.message)
            adminList()
        }).catch((err) => {
            console.log(err);
        })
}

// 分页大小改变
const handleSizeChange = (val) => {
    pageSize.value = val
    adminList()
}

// 页码改变
const handleCurrentChange = (val) => {
    currentPage.value = val
    adminList()
}

//获取角色名称列表
const adminList = () => {
    request.get('/role/page', {
        page: currentPage.value,
        size: pageSize.value
    })
        .then((res) => {
            // console.log(res);
            if (res.code != 200) {
                ElMessage.error(res.message)
            }
            total.value = res.data.count;
            tableData.value = res.data.list;

        }).catch((err) => {
            console.error('获取失败：', err)
        })
}

// 获取菜单选项列表
const fetchRoles = () => {
    request.get('/role/getmenu')
        .then((res) => {
            // console.log(res);
            roleOptions1.value = res.data.menuList;
            // console.log(roleOptions.value[0].roleId);

        }).catch((err) => {
            console.log(err);

        })
}

// 获取角色选项列表
const fetchMenus = () => {
    request.get('/role/getrole')
        .then((res) => {
            // console.log(res);
            roleOptions.value = res.data.rolePermissionList;
            // console.log(roleOptions.value[0].roleId);

        }).catch((err) => {
            console.log(err);

        })
}

</script>

<style>
.crud-container {
    background-color: #fff;
    padding: 20px;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.search-area {
    margin-bottom: 20px;
    padding-bottom: 20px;
    border-bottom: 1px solid #ebeef5;
}

.operation-area {
    margin-bottom: 20px;
}

.table-area {
    margin-bottom: 20px;
}

.pagination-area {
    display: flex;
    justify-content: flex-end;
    margin-top: 20px;
}

.pagination-area span {
    padding-left: 10px;
}

.search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.el-button [class*="el-icon"]+span {
    margin-left: 5px;
}

.search-form .el-form-item {
    min-width: 190px;
}

.el-form-item span {
    /* padding-left: 10px; */
}

.el-formitem {
    width: 225px;
}
</style>